package operator.function.do_;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import util.Printer;
import util.RxJavaHelper;
import util.ThreadHelper;

class DoAfterTerminateOperator {

    public static void main(String[] args) {
        doAfterTerminate();
    }

    //取消订阅时不执行
    static void doAfterTerminate(){
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                emitter.onNext(1);
                emitter.onNext(2);
                emitter.onNext(3);
                emitter.onError(RxJavaHelper.getException());
//                emitter.onComplete();
            }
        })
                .doAfterTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        Printer.print("doAfterTerminate");
                    }
                })
                .subscribe(new Observer<Integer>() {

                    Disposable disposable;

                    @Override
                    public void onSubscribe(Disposable disposable) {
                        Printer.print("doAfterTerminate onSubscribe");
                        this.disposable = disposable;
                    }

                    @Override
                    public void onNext(Integer integer) {
                        Printer.print("doAfterTerminate onNext integer = " + integer);
                        if(integer == 2){
//                            disposable.dispose();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Printer.print("doAfterTerminate onError");
                    }

                    @Override
                    public void onComplete() {
                        Printer.print("doAfterTerminate onComplete");
                    }
                });
        ThreadHelper.sleep();
    }


}
